package com.smartmedical.auth.doctor.controller;

import com.smartmedical.auth.doctor.convert.QualityDoctorConvert;
import com.smartmedical.auth.doctor.doctordomain.entity.DoctorEnity;
import com.smartmedical.auth.doctor.doctordomain.vo.DoctorVo;
import com.smartmedical.auth.doctor.service.DoctorService;
import com.smartmedical.common.core.domain.HealthR;
import com.smartmedical.common.security.service.TokenService;
import com.smartmedical.system.api.domain.SysUser;
import com.smartmedical.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/doctor")
public class DoctorController {

    @Autowired
    DoctorService doctorService;
    @Autowired
    private TokenService tokenService;

    @PostMapping("v1/login")
    public HealthR<?> login(@RequestParam String email, @RequestParam String pwd) throws Exception {
        DoctorEnity userInfo = doctorService.docLogin(email, pwd);
        //loginUser赋值
        LoginUser loginUser =creatLoginUser(userInfo);

        Map<String, Object> token = tokenService.createToken(loginUser);
        Object accessToken = token.get("access_token");

        DoctorVo doctorVo = createDoctorVo(userInfo,accessToken);


        return HealthR.ok(doctorVo);
    }


    private DoctorVo createDoctorVo(DoctorEnity userInfo, Object accessToken) {

        DoctorVo doctorVo = QualityDoctorConvert.INSTANCE.convert(userInfo);

        doctorVo.setDoctorId(userInfo.getId());
        doctorVo.setSessionId(accessToken.toString());
        doctorVo.setJiGuangPwd(userInfo.getPwd());
        if (doctorVo.getImagePic() != null) {
            doctorVo.setWhetherHaveImagePic(1);
        }else{
            doctorVo.setWhetherHaveImagePic(0);
        }


        return doctorVo;
    }

    private LoginUser creatLoginUser(DoctorEnity userInfo) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
        loginUser.setUsername(userInfo.getEmail());
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userInfo.getId());
        sysUser.setUserName(userInfo.getEmail());
        sysUser.setDeptId(userInfo.getDepartmentId());
        sysUser.setPhonenumber(userInfo.getPhone());

        loginUser.setSysUser(sysUser);
        return loginUser;
    }


}
